/**
 * Copyright (c) 2020 kedacom
 * OpenATC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 **/
<template>
  <div class="homeLayouts">
    <div class="top">
      <el-row :gutter="20">
        <el-col :span="8" v-for="(card, index) in topPart" :key="index">
          <OpenATCCard width="100%" height="100%" :ishasTitle="false">
            <div @click="handleClickToPage(card.name)" slot="cardContent" class="animationPart">
              <!-- <div class="imagebox" id="imagebox"> -->
                <img class="imgindex" :src="card.imageurl">
                <!-- <LottieAnim v-if="Visible" :Width="Width" :Height="Height" :Options="card.options" /> -->
                <!-- <div :class="card.className" :style="{height: imgHeight, backgroundSize: imgWidth + ' ' + imgHeight}"></div> -->
              <!-- </div> -->
              <div class="toPage">
                <div :style="{ marginTop: toPageMarginTop, marginBottom: toPageMarginBottom }">
                  {{
                    (card.name === 'devicemaneger'&&menuDevice)?menuDevice
                    :(card.name === 'greenwaveoptimization'&&menuRouteOptimize)?menuRouteOptimize
                    :(card.name === 'secretservicemission'&&menuDutyroute)?menuDutyroute
                    :$t(`openatc.home.${[card.name]}`)
                  }}
                  </div>
                <!-- <i class="iconfont icon-qianwang" @click="handleClickToPage(card.name)"></i> -->
              </div>
              <div class="bottomBorder"></div>
            </div>
          </OpenATCCard>
        </el-col>
      </el-row>
      <!-- <el-row :gutter="20">
        <el-col :span="16">
          <OpenATCCard width="100%" height="100%" :title="$t('openatc.home.devicestatus')">
            <div slot="cardContent" class="chart">
              <DevsStateChart :chartData="chartData"/>
            </div>
          </OpenATCCard>
        </el-col>
        <el-col :span="8">
          <OpenATCCard width="100%" height="100%" :title="$t('openatc.home.faultlist')">
            <div slot="cardContent" class="list">
              <FaultList :faultList="faultList"/>
            </div>
          </OpenATCCard>
        </el-col>
      </el-row> -->
    </div>
    <div class="bottom">
      <el-row :gutter="20">
        <el-col :span="8" v-for="(card, index) in toPagePart" :key="index">
          <OpenATCCard width="100%" height="100%" :ishasTitle="false">
            <div @click="handleClickToPage(card.name)" slot="cardContent" class="animationPart">
              <!-- <div class="imagebox" id="imagebox"> -->
                <!-- <LottieAnim v-if="Visible" :Width="Width" :Height="Height" :Options="card.options" /> -->
                <img class="imgindex" :src="card.imageurl">
                <!-- <div :class="card.className" :style="{height: imgHeight, backgroundSize: imgWidth + ' ' + imgHeight}"></div> -->
              <!-- </div> -->
              <div class="toPage">
                <div :style="{ marginTop: toPageMarginTop, marginBottom: toPageMarginBottom }">{{
                  (card.name === 'faultrecord'&&menuFaultRecord)?menuFaultRecord
                  :(card.name === 'usermanager'&&menuUsermanager)?menuUsermanager
                  :(card.name === 'operationrecord'&&menuOperateRecord)?menuOperateRecord:$t(`openatc.home.${[card.name]}`)}}</div>
                <!-- <i class="iconfont icon-qianwang" @click="handleClickToPage(card.name)"></i> -->
              </div>
              <div class="bottomBorder"></div>
            </div>
          </OpenATCCard>
        </el-col>
      </el-row>
    </div>
  </div>
</template>
<script>
import OpenATCCard from '../../components/OpenATCCards/index'
import DevsStateChart from './devsStateChart'
import FaultList from './faultList'
// import router from '../../router'
import { GetAllDevice } from '../../api/device'
import { SystemconfigApi } from '../../api/systemconfig.js'
import { GetFaultRange } from '../../api/fault'
import LottieAnim from './lottieDemo/index'
import deviceAnim from '../../../static/lottiejson/deviceManager.json'
import userAnim from '../../../static/lottiejson/userManager.json'
import operatAnim from '../../../static/lottiejson/operationRecord.json'
import { getMessageByCode } from '../../utils/responseMessage'
import faultrecord from '../../assets/home/faultrecord.png'
import usermanager from '../../assets/home/usermanager.png'
import operationrecord from '../../assets/home/operation.png'
import devicemaneger from '../../assets/home/roadmannage.png'
import greenwave from '../../assets/home/greenwave.png'
import secretservice from '../../assets/home/secretservice.png'
export default {
  data () {
    return {
      Width: 340,
      Height: 236,
      menuDevice: '',
      menuFaultRecord: '',
      menuOperateRecord: '',
      menuRouteOptimize: '',
      menuLogs: '',
      menuUsermanager: '',
      menuDutyroute: '',
      Visible: false,
      getDevsDataTimer: Object,
      toPageMarginTop: '17px',
      toPageMarginBottom: '20px',
      toPagePart: [{
        className: 'fault-record',
        name: 'faultrecord',
        imageurl: faultrecord,
        options: {
          animationData: deviceAnim, loop: false, autoplay: false
        }
      }, {
        className: 'user-manage',
        name: 'usermanager',
        imageurl: usermanager,
        options: {
          animationData: userAnim, loop: false, autoplay: false
        }
      }, {
        className: 'operation-record',
        name: 'operationrecord',
        imageurl: operationrecord,
        options: {
          animationData: operatAnim, loop: false, autoplay: false
        }
      }
      ],
      topPart: [{
        className: 'device-manage',
        name: 'devicemaneger',
        imageurl: devicemaneger,
        options: {
          animationData: deviceAnim, loop: false, autoplay: false
        }
      }, {
        className: 'green-wave-optimization',
        imageurl: secretservice,
        name: 'greenwaveoptimization',
        options: {
          animationData: deviceAnim, loop: false, autoplay: false
        }
      }, {
        className: 'secret-service-mission',
        imageurl: greenwave,
        name: 'secretservicemission',
        options: {
          animationData: deviceAnim, loop: false, autoplay: false
        }
      }
      ],
      // faultTypeMap 故障种类，前端写死的假数据
      // faultTypeMap: new Map([[1, '检测器报警'], [2, '灯故障'], [3, '断电故障'], [4, '通讯故障']]),
      faultTypeMap: new Map([[201, '灯控板在线个数异常'], [202, '灯组红绿同亮'], [203, '所有灯组红灯全灭'], [204, '绿冲突'], [1, '检测器报警'], [2, '灯故障'], [3, '断电故障'], [4, '通讯故障']]),
      faultList: [],
      chartData: [{
        name: '在线',
        value: 0
      },
      {
        name: '离线',
        value: 0
      }, {
        name: '故障',
        value: 0
      }]
    }
  },
  components: {
    OpenATCCard,
    DevsStateChart,
    FaultList,
    LottieAnim
  },
  created () {
    this.getMemu()
  },
  methods: {
    getMemu () {
      // return new Promise((resolve, reject) => {
      let reqData = {
        module: 'menu',
        isValid: true
      }
      SystemconfigApi.GetSystemconfigList(reqData).then((data) => {
        let res = data.data
        if (!res.success) {
          console.log('datas:' + res)
          throw new Error('get JupyterUrl error')
        } else {
          for (let config of data.data.data) {
            // 主页
            if (config['key'] === 'home') {
              this.menuHome = config['value']
            }
            // 基础管理
            if (config['key'] === 'base') {
              this.menuBase = config['value']
            }
            // 交通分析
            if (config['key'] === 'statistics') {
              this.menuStatistics = config['value']
            }
            // 交通优化
            if (config['key'] === 'optimization') {
              this.menuOptimization = config['value']
            }
            // 交通干预
            if (config['key'] === 'interrupt') {
              this.menuInterrupt = config['value']
            }
            // 地图
            if (config['key'] === 'gis') {
              this.menuGis = config['value']
            }
            // 系统日志
            if (config['key'] === 'logs') {
              this.menuLogs = config['value']
            }
            // 权限管理
            if (config['key'] === 'auth') {
              this.menuAuth = config['value']
            }
            // 路口管理
            if (config['key'] === 'device') {
              this.menuDevice = config['value']
            }
            if (config['key'] === 'greenWaveOptimize') {
              this.menugreenwave = config['value']
            }
            if (config['key'] === 'basicdata') {
              this.menuBasicData = config['value']
            }
            if (config['key'] === 'operationfrequency') {
              this.menuOperation = config['value']
            }
            if (config['key'] === 'devicefault') {
              this.menuDeviceFault = config['value']
            }
            if (config['key'] === 'platformstatistics') {
              this.menuPlatform = config['value']
            }
            // 路口管控
            if (config['key'] === 'dutyroute') {
              this.menuDutyroute = config['value']
            }
            // 干线协调
            if (config['key'] === 'routeOptimize') {
              this.menuRouteOptimize = config['value']
            }
            if (config['key'] === 'gisCoordinateRoute') {
              this.menuGisCoordinateRoute = config['value']
            }
            if (config['key'] === 'gisDutyRoute') {
              this.menuGisDutyRoute = config['value']
            }
            if (config['key'] === 'gisDevice') {
              this.menuGisDevice = config['value']
            }
            if (config['key'] === 'operaterecord') {
              this.menuOperateRecord = config['value']
            }
            if (config['key'] === 'faultrecord') {
              this.menuFaultRecord = config['value']
            }
            if (config['key'] === 'platformrecord') {
              this.menuPlatformRecord = config['value']
            }
            if (config['key'] === 'organization') {
              this.menuOrganization = config['value']
            }
            if (config['key'] === 'user') {
              this.menuUsermanager = config['value']
            }
            if (config['key'] === 'role') {
              this.menuRole = config['value']
            }
            if (config['key'] === 'permission') {
              this.menuPermission = config['value']
            }
            if (config['key'] === 'setting') {
              this.menuSystemsettings = config['value']
            }
            if (config['key'] === 'thirdPlatform') {
              this.menuThirdPlatform = config['value']
            }
          }
          // resolve(data.data.data)
        }
      })
      // })
    },
    calculateHeight () {
      // 浏览器可视区域的高
      let viewH = document.documentElement.clientHeight - 10
      this.toPageMarginTop = (17 / 1080 * viewH).toFixed(0) + 'px'
      this.toPageMarginBottom = (17 / 1080 * viewH).toFixed(0) + 'px'
      this.Width = document.getElementById('imagebox').clientWidth - 44
      this.Height = document.getElementById('imagebox').clientHeight
      this.Visible = true
    },
    handleClickToPage (name) {
      switch (name) {
        case 'greenwaveoptimization': this.$router.push({ path: '/routeOptimize' })
          this.$store.dispatch('SetActiveMenuName', 'route')
          break
        case 'secretservicemission': this.$router.push({ path: '/dutyroute' })
          this.$store.dispatch('SetActiveMenuName', 'dutyroute')
          break
        case 'devicemaneger': this.$router.push({ path: '/device' })
          this.$store.dispatch('SetActiveMenuName', 'device')
          break
        case 'faultrecord': this.$router.push({ path: '/faultrecord' })
          this.$store.dispatch('SetActiveMenuName', 'logs')
          break
        case 'usermanager': this.$router.push({ path: '/user' })
          this.$store.dispatch('SetActiveMenuName', 'auth')
          break
        case 'operationrecord': this.$router.push({ path: '/operaterecord' })
          this.$store.dispatch('SetActiveMenuName', 'logs')
          break
        default: this.$router.push({ path: '/' })
      }
    },
    resetData () {
      this.chartData = [{
        name: '在线',
        value: 0
      },
      {
        name: '离线',
        value: 0
      }, {
        name: '故障',
        value: 0
      }]
    },
    getdata () {
      GetAllDevice().then(res => {
        if (!res.data.success) {
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return
        }
        this.resetData()
        res.data.data.forEach(ele => {
          if (ele.state === 'UP') {
            this.chartData[0].value++
          }
          if (ele.state === 'DOWN') {
            this.chartData[1].value++
          }
          if (ele.state === 'FAULT') {
            this.chartData[0].value++
            this.chartData[2].value++
          }
        })
      })
      let reqData = {
        'isCurrentFault': true
      }
      GetFaultRange(reqData).then(res => {
        let list = {}
        if (!res.data.success) {
          this.$message.error(getMessageByCode(res.data.code, this.$i18n.locale))
          return false
        } else {
          list = res.data.data
        }
        this.faultList = list.content || []
      })
    }
  },
  mounted () {
    this.calculateHeight()
    this.getdata()
    this.getDevsDataTimer = setInterval(() => {
      this.getdata()
    }, 60000)
    const _this = this
    window.onresize = function () {
      // 动画大小自适应
      _this.Width = document.getElementById('imagebox').clientWidth
      _this.Height = document.getElementById('imagebox').clientHeight
      _this.Visible = false
      _this.$nextTick(() => {
        _this.Visible = true
      })
    }
  },
  destroyed () {
    clearInterval(this.getDevsDataTimer)
  }
}
</script>

<style lang="scss" scoped>
.bottomBorder{
  //居中的border
  width: 34px;
  height: 3px;
  background-color: #299bcc;
  position: absolute;
  left: 47%;
}
</style>
